package com.shop.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Slf4j
@Component("fileUtil")
public class FileUtil {

    @Autowired
    private FtpUtil ftpUtil;

    private static boolean isHaveTemp = false;

    @Value("${ftp.localTemp.path}")
    private String localPath;

    public String saveToLocalOrFtp(MultipartFile file, boolean isUploadToServer){
        /*  1、获取文件名 */
        String fileName = file.getOriginalFilename().replaceAll(" ", "_");

        /* 2、获取文件后缀名和 */
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".")+1);
        String filePrefixName = fileName.substring(0, fileName.lastIndexOf("."));

        /* 3、重新生成需要被上传文件名 */
        String uploadName = filePrefixName + "(" + UUID.randomUUID().toString() + ")." + fileExtensionName;

        if(!tempPathIsExistAndAutoCreate(getLocalStorePath())){
            log.info("零时存放图片文件夹不存在，创建失败。");
            return "零时存放图片文件夹不存在，创建失败";
        }
        /* 4、上传文件到本地 */
        log.info("开始上传文件，上传文件的文件名:"+fileName+",上传的路径:"+ getLocalStorePath() + ",新文件名:"+uploadName);
        File saveToPath = new File(getLocalStorePath() + File.separator + uploadName);
        try {
            file.transferTo(saveToPath);
        } catch (IOException e) {
            log.info("保存上传的文件失败:[" + e.getMessage() + "]");
            return "保存上传的文件失败";
        }
        /* 4、上传文件到ftp服务器*/
        if (isUploadToServer) {
           return saveToFTPServer(uploadName, this.localPath,false);
        }
        return "保存上传的文件失败";
    }

    private static boolean tempPathIsExistAndAutoCreate(String path) {
        File tempPath = new File(path);
        if(!tempPath.exists()){
            return tempPath.mkdirs();
        }
        return true;
    }

    public  String getLocalStorePath(){
        String path = FileUtil.class.getClassLoader().getResource("").getPath() + this.localPath  + File.separator;
        if (!isHaveTemp) {
            isHaveTemp = tempPathIsExistAndAutoCreate(path);
            if (!isHaveTemp) log.info("创建零时存放文件目录失败");
        }
        return path;
    }

    public  File getLocalFile(String fileName){
        return new File(getLocalStorePath() + fileName);
    }


    public  String saveToFTPServer(String fileName,String remotePath,boolean isAutoDelete){
        /*1.获取需要上传FTP的本地零时文件*/
        File localFile = getLocalFile(fileName);
        log.info(localFile.getAbsolutePath());
        /*1.1、如果找不到该文件，返回一个'找不到文件错误'。*/
        if(!localFile.exists()){ return "找不到文件错误"; }
        /*2、将保存在本地的文件上传到FTP服务器。*/
        try {
            InputStream inputStream = new FileInputStream(localFile);
            ftpUtil.upload(inputStream,fileName,remotePath);
        } catch (Exception e) {
            log.info("保存上传的文件失败:[" + e.getMessage() + "]");
            return "保存上传的文件失败";
        }
        /*3、删除本地零时保存文件*/
        if (isAutoDelete) if(!localFile.delete()) log.info("删除本地零时保存文件失败");
        return  String.format("%s/%s", remotePath, fileName);
    }
}
